import time

import pymysql.cursors
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
import csv


def getData_start(name, url):
    # # 获取数据库游标
    # connect = pymysql.Connect('192.168.1.72', 'root', 'root', 'TV18')
    # # 获取数据库游标
    # cursor = connect.cursor()
    # # SQL 插入语句
    # StringSql = "INSERT INTO yintao (name,url)VALUES ('%s', '%s')" % (name,
    #                                                                   url)
    # try:
    #     # 执行SQL
    #     cursor.execute(StringSql)
    #     # 提交到数据库执行
    #     connect.commit()
    # except Exception as e:
    #     # 如果发生错误则回滚
    #     connect.rollback()
    #     print(e)
    # # 关闭数据库连接
    # connect.close()

    # 写入CSV文件
    with open("vip.csv", 'a+', newline='', encoding='utf-8') as f:
        csv_write = csv.writer(f)
        data_row = [name, url]
        csv_write.writerow(data_row)


def openUrl(browser, index, name):
    try:
        # 切换到详情页
        for handle in browser.window_handles:
            if handle == index:
                continue
        info = handle
        if index == info:
            for handle in browser.window_handles:
                if handle == index:
                    continue
                browser.switch_to.window(handle)
                browser.close()
            return
        browser.switch_to.window(info)

        # 点击vip图标去广告
        try:
            wait.until(
                EC.presence_of_element_located((
                    By.XPATH,
                    '/html/body/div/span/div[1]/div/div[2]/div[3]/div[1]/div[2]'
                )), "获取视频框失败")
            # vip = browser.find_element_by_id("add-bnt")
            # browser.execute_script('arguments[0].click()', vip)
            time.sleep(5)
            browser.find_element_by_xpath("/html/body/div/span/div[1]/div/div[2]/div[3]/div[1]/div[2]/div[2]/div[4]/div[2]/button").click()
            print("执行了消除图标按钮")
            time.sleep(21)
        except Exception as e:
            print("vip图标不存在")
        time.sleep(3)
        # 去除错误信息(这个步骤无效.)
        try:
            # 看哈是否能去除弹窗
            js = 'document.getElementsByClassName("mango_msg")[0].style.display="none";'
            browser.execute_script(js)
        except Exception as e:
            print(e)
        # 获取下载按钮
        wait.until(EC.presence_of_element_located((By.ID, 'downloadSvg')),
                   "获取下载按钮失败")
        xiazai = browser.find_element_by_id("downloadSvg")
        # 点击下载按钮
        browser.execute_script('arguments[0].click()', xiazai)
        # 切换下载窗口
        for handle in browser.window_handles:
            if handle == index:
                continue
            if handle == info:
                continue
            browser.switch_to.window(handle)
        # 保存下载地址
        wait.until(
            EC.presence_of_element_located((By.XPATH, '/html/body/video')),
            "获取播放页失败")
        getData_start(name, browser.current_url)
        print(browser.current_url)
        # 关闭下载页窗口
        browser.close()
        # 关闭详情页窗口
        for handle in browser.window_handles:
            if handle == index:
                continue
            browser.switch_to.window(handle)
            browser.close()
    except Exception as e:
        print(e)
        for handle in browser.window_handles:
            if handle == index:
                continue
            browser.switch_to.window(handle)
            browser.close()

# 打开视频详情
def fanye():
    for name in range(1, 26):
        b = browser.find_element_by_xpath(
            "/html/body/div/span/div[1]/div/div[1]/div[3]/div[%s]/div[2]" %
            name)
        browser.execute_script('arguments[0].click()', b)
        time.sleep(1)
        openUrl(browser, index, b.text)
        # 切换回主页
        browser.switch_to.window(index)
        time.sleep(1)


chrome_options = webdriver.FirefoxOptions()
profile = webdriver.FirefoxProfile()
# 禁止图片加载
profile.set_preference('permissions.default.image', 2)
# chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')

#get直接返回，不再等待界面加载完成
desired_capabilities = DesiredCapabilities.FIREFOX
desired_capabilities["pageLoadStrategy"] = "none"

browser = webdriver.Firefox(firefox_options=chrome_options,
                            firefox_profile=profile)
mainUrl = "https://cherry31.com/#/film/vip"
browser.get(mainUrl)
# 设定等待时间
wait = WebDriverWait(browser, 30)
# 当检查到存在时放弃等待
try:
    wait.until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, '登录')),"登录失败")
    # 执行按钮
    browser.find_element(By.PARTIAL_LINK_TEXT, '登录').send_keys(Keys.ENTER)
    time.sleep(2)
    browser.find_element_by_xpath(
        "//*[@id='app']/div/div[2]/div[1]/div[2]/div[1]/input").send_keys(
            "18108192859")
    browser.find_element_by_xpath(
        "//*[@id='app']/div/div[2]/div[1]/div[2]/div[2]/input").send_keys(
            "991426")
    browser.find_element_by_xpath(
        "//*[@id='app']/div/div[2]/div[1]/div[2]/div[4]").click()
    # 获取主页窗口句柄
    index = browser.current_window_handle
    # 等待当前页面元素出现
    wait.until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, 'film-item')))
    time.sleep(3)
    # 首页
    wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/span/div[1]/div/div[1]/div[4]/div/button[1]')),
               "获取首页失败")
    homePage = browser.find_element_by_xpath(
        "/html/body/div/span/div[1]/div/div[1]/div[4]/div/button[1]")

    # 下一页
    wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/span/div[1]/div/div[1]/div[4]/div/button[4]')),
               "获取下一页失败")
    LastPage = browser.find_element_by_xpath(
        "/html/body/div/span/div[1]/div/div[1]/div[4]/div/button[4]")

    # 获取当前页
    wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/span/div[1]/div/div[1]/div[4]/div/div/input')),
               "获取当前页失败")
    page = browser.find_element_by_xpath(
        "/html/body/div/span/div[1]/div/div[1]/div[4]/div/div/input")
    page.clear()
    page.send_keys('1')
    number = page.get_attribute("value")
    print("当前页",number)

    # 执行跳转指定页
    go = browser.find_element_by_xpath(
        "/html/body/div/span/div[1]/div/div[1]/div[4]/div/button[3]")
    browser.execute_script('arguments[0].click()', go)
    time.sleep(2)
    # 跳转到下一页
    for i in range(1, 11):
        browser.execute_script('arguments[0].click()', LastPage)
        time.sleep(2)
        print("当前好多页了",i+0)
        fanye()
        
    browser.quit()
except Exception as e:
    print(e)
    browser.quit()
